package org.dromara.system.job;

import com.aizuda.snailjob.client.job.core.annotation.JobExecutor;
import com.aizuda.snailjob.client.job.core.dto.JobArgs;
import com.aizuda.snailjob.client.model.ExecuteResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.system.domain.DeviceAlarm;
import org.dromara.system.mapper.DeviceAlarmMapper;
import org.dromara.system.mapper.DeviceMapper;
import org.dromara.system.service.IDeviceAlarmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@JobExecutor(name = "CheckDeviceAlarmStatusJob")
@Slf4j
@Component
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class CheckDeviceAlarmStatusJob {

    private final DeviceAlarmMapper deviceAlarmMapper;

    public ExecuteResult jobExecute(JobArgs jobArgs) {
        List<DeviceAlarm> deviceAlarms = deviceAlarmMapper.selectList(new LambdaQueryWrapper<DeviceAlarm>().eq(DeviceAlarm::getJobStatus, 0).eq(DeviceAlarm::getStatus, 1));
        if (deviceAlarms.isEmpty()) return ExecuteResult.success("暂无数据");
        for (DeviceAlarm deviceAlarm : deviceAlarms) {
            updateDeviceStatus(deviceAlarm.getVariableId());
            //设备下的正常传感器的设备数量
            Long normalDeviceCount = deviceAlarmMapper.selectNormalDeviceCount(deviceAlarm.getDeviceId(), 1);
            //设备下的传感器的设备数量
            Long count = deviceAlarmMapper.selectAllDeviceCount(deviceAlarm.getDeviceId());
            if (count == 0L) return ExecuteResult.success("暂无数据");
            if (normalDeviceCount.equals(count)) {
                deviceAlarmMapper.updateDeviceStatusById(deviceAlarm.getDeviceId());
                deviceAlarmMapper.updateJobStatus(deviceAlarm.getId());
            }
        }
        return ExecuteResult.success("批量更新状态成功");
    }

    private void updateDeviceStatus(Long variableId) {
        deviceAlarmMapper.updateVariableStatusById(variableId);
    }

//{
//    "message": null,
//    "pager": null,
//    "result": null,
//    "resultMap": null,
//    "results": [
//        {
//            "sensor": "WY010102  ",
//            "time": "2025/01/15 01:41:00",
//            "type": "WY",
//            "typename": "位移",
//            "value": 0.718
//        },
//    ]
//}

}
